﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Rison.BusinessFacade.Common;
using Rison.BusinessFacade.Helper;
using Rison.BusinessFacade.Entity.NRBZ;
using Rison.BusinessFacade.Facade.NRBZ;

using System.IO;

namespace Rison.Web.ascx
{
    public partial class FileUpload : System.Web.UI.UserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (AutoLoadAttachment && parentId > 0)
                {
                    LoadAttachment(parentId);
                }
            }
        }

        /// <summary>
        /// 附件所属的对象的主键值。
        /// </summary>
        private long parentId
        {
            get
            {
                if (StringHelper.IsNumber(Request.QueryString["key"]))
                {
                    return Convert.ToInt64(Request.QueryString["key"]);
                }
                else if (StringHelper.IsNumber(Request.QueryString["parentId"]))
                {
                    return Convert.ToInt64(Request.QueryString["parentId"]);
                }
                return 0;
            }
        }

        #region "  控件init时，外部传入的参数。  "
        /// <summary>
        /// 编辑对象时，是否自动加载附件列表。
        /// 默认为：自动加载。
        /// </summary>
        public bool AutoLoadAttachment
        {
            get { return (ViewState["AutoLoadAttachment"] == null) ? true : Convert.ToBoolean(ViewState["AutoLoadAttachment"]); }
            set { ViewState["AutoLoadAttachment"] = value; }
        }

        /// <summary>
        /// 保存附件的数据表。
        /// 默认将使用Sys_Attachment，用于自动绑定附件列表。
        /// </summary>
        public string AttachmentTablename
        {
            get { return (ViewState["AttachmentTablename"] == null) ? string.Empty : ViewState["AttachmentTablename"].ToString(); }
            set { ViewState["AttachmentTablename"] = value; }
        }

        /// <summary>
        /// 保存附件的数据表中，附件所属的主对象的字段名称。
        /// 默认将使用ParentId，用于自动绑定附件列表。
        /// </summary>
        public string ParentKeyName
        {
            get { return (ViewState["ParentKeyName"] == null) ? "ParentId" : ViewState["ParentKeyName"].ToString(); }
            set { ViewState["ParentKeyName"] = value; }
        }

        /// <summary>
        /// 附件的上传路径，格式如：\file\atts\。若没有指定，则使用系统默认路径。
        /// </summary>
        public string UploadFolder
        {
            get { return (ViewState["UploadFolder"] == null) ? string.Empty : ViewState["UploadFolder"].ToString(); }
            set { ViewState["UploadFolder"] = value; }
        }

        /// <summary>
        /// 上传的附件的大小限制，单位M。
        /// 若没有指定，则使用系统默认配置值。0表示不限制大小。
        /// </summary>
        public int LimitedSize
        {
            get { return (ViewState["LimitedSize"] == null) ? 0 : Convert.ToInt32(ViewState["LimitedSize"]); }
            set { ViewState["LimitedSize"] = value; }
        }

        /// <summary>
        /// 允许上传的附件的扩展名列表，格式如：.jpg,.gif,.doc。以英文逗号间隔
        /// </summary>
        public string AllowedExtensions
        {
            get { return (ViewState["AllowedExtensions"] == null) ? string.Empty : ViewState["AllowedExtensions"].ToString(); }
            set { ViewState["AllowedExtensions"] = value; }
        }

        private List<string> AllowedExtensionList
        {
            get
            {
                List<string> enList = null;

                if (!string.IsNullOrEmpty(AllowedExtensions))
                {
                    enList = new List<string>();
                    string[] ens = AllowedExtensions.Split(Convert.ToChar(","));

                    foreach (string en in ens)
                        enList.Add(en);

                    ens = null;
                }
                return enList;
            }
        }
        #endregion


        #region "  已上传的附件列表  "

        private List<SysAttachment> _attachments = null;

        /// <summary>
        /// 已上传的附件列表。
        /// </summary>
        public List<SysAttachment> Attachments
        {
            get
            {
                if (_attachments == null || _attachments.Count != drpAtts.Items.Count)
                {
                    _attachments = new List<SysAttachment>();

                    for (int i = 0; i < drpAtts.Items.Count; i++)
                    {
                        SysAttachment att = new SysAttachment();
                        att.FileName = this.drpAtts.Items[i].Text;
                        att.FilePath = this.drpAtts.Items[i].Value;
                        att.FileSize = this.lstFileSize.Items[i].Text;
                        att.Extension = this.lstFileExtension.Items[i].Text;
                        att.ContentType = this.lstContentType.Items[i].Text;

                        _attachments.Add(att);
                    }
                }

                return _attachments;
            }
        }
        #endregion


        #region "  所有附件的总字节大小  "
        /// <summary>
        /// 所有附件的总字节大小。
        /// </summary>
        public int TotalFileSize
        {
            get
            {
                int totalsize = 0;
                try
                {
                    foreach (ListItem item in drpAtts.Items)
                    {
                        FileInfo info = new FileInfo(Server.MapPath("~" + item.Value));
                        if (info.Exists)
                            totalsize += Convert.ToInt32(info.Length);
                        info = null;
                    }
                }
                catch { }

                return totalsize;
            }
        }
        //public int TotalFileSize
        //{
        //    get { return ViewState["TotalFileSize"] == null ? 0 : Convert.ToInt32(ViewState["TotalFileSize"]); }
        //    set { ViewState["TotalFileSize"] = value; }
        //}
        #endregion


        /// <summary>
        /// 控件Load时，会自动判断parentId，如果存在则加载对应的附件列表。
        /// 若初始时没有传入，可在外部手动调用，传入该ID来加载附件。
        /// </summary>
        /// <param name="parentId">附件所属对象的key值。</param>
        public void LoadAttachment(long parentId)
        {
            StringBuilder condition = new StringBuilder();
            condition.AppendFormat("{0}={1}", ParentKeyName, parentId.ToString());

            DataSet attachments = new SysAttachmentFacade(AttachmentTablename).GetDataBy(condition.ToString());

            this.drpAtts.DataSource = attachments;
            this.drpAtts.DataValueField = "FilePath";
            this.drpAtts.DataTextField = "FileName";
            this.drpAtts.DataBind();

            this.lstFileSize.DataSource = attachments;
            this.lstFileSize.DataTextField = "FileSize";
            this.lstFileSize.DataBind();

            this.lstFileExtension.DataSource = attachments;
            this.lstFileExtension.DataTextField = "Extension";
            this.lstFileExtension.DataBind();

            this.lstContentType.DataSource = attachments;
            this.lstContentType.DataTextField = "ContentType";
            this.lstContentType.DataBind();

            condition = null; attachments.Dispose(); attachments = null;
        }

        public void btnUpload_Click(object sender, ImageClickEventArgs e)
        {
            if (this.fileUpload.PostedFile != null)
            {
                FileUploader uploader = new FileUploader();
                uploader.SetSizeUnit(FileSize.MegaByte);
                uploader.FileUploadFolder = (string.IsNullOrEmpty(UploadFolder)) ? GlobalParams.Instance.AttachmentUploadUrl : UploadFolder;
                if (uploader.Upload(this.fileUpload.PostedFile, (LimitedSize > 0) ? LimitedSize : GlobalParams.Instance.maxAttachmentSize, AllowedExtensionList) == false)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "errMsg", "<script type=\"text/javascript\">alert('" + uploader.Message + "');</script>");
                }
                else
                {
                    this.drpAtts.Items.Add(new ListItem(uploader.OriginalName, uploader.UploadedPath));
                    this.lstFileSize.Items.Add(uploader.FileLength);
                    this.lstFileExtension.Items.Add(uploader.Extension);
                    this.lstContentType.Items.Add(uploader.ContentType);

                    //TotalFileSize += uploader.FileByteSize;
                }

              
            }
        }

        public void btnUpload_Click()
        {
            if (this.fileUpload.PostedFile != null)
            {
                FileUploader uploader = new FileUploader();
                uploader.SetSizeUnit(FileSize.MegaByte);
                uploader.FileUploadFolder = (string.IsNullOrEmpty(UploadFolder)) ? GlobalParams.Instance.AttachmentUploadUrl : UploadFolder;
                if (uploader.Upload(this.fileUpload.PostedFile, (LimitedSize > 0) ? LimitedSize : GlobalParams.Instance.maxAttachmentSize, AllowedExtensionList) == false)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "errMsg", "<script type=\"text/javascript\">alert('" + uploader.Message + "');</script>");
                }
                else
                {
                    this.drpAtts.Items.Add(new ListItem(uploader.OriginalName, uploader.UploadedPath));
                    this.lstFileSize.Items.Add(uploader.FileLength);
                    this.lstFileExtension.Items.Add(uploader.Extension);
                    this.lstContentType.Items.Add(uploader.ContentType);

                    //TotalFileSize += uploader.FileByteSize;
                }


            }
        }

        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (this.drpAtts.SelectedItem != null)
            {
                try
                {
                    FileHelper.DeleteFile(Server.MapPath("~" + drpAtts.SelectedValue));

                    //FileInfo info = new FileInfo(Server.MapPath("~" + drpAtts.SelectedValue));
                    //if (info.Exists)
                    //{
                    //    TotalFileSize = TotalFileSize - Convert.ToInt32(info.Length);

                    //    FileHelper.DeleteFile(info.FullName);
                    //}
                    //info = null;                    
                }
                catch { }

                int index = drpAtts.SelectedIndex;
                this.drpAtts.Items.RemoveAt(index);
                this.lstFileSize.Items.RemoveAt(index);
                this.lstFileExtension.Items.RemoveAt(index);
                this.lstContentType.Items.RemoveAt(index);
            }
        }
    }
}